package com.cwt_taxi_xa.util;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;
import okio.Sink;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.R;
import com.cwt_taxi_xa.ActivityWaitQD.checkSJinfor;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.data.SijiInfo;
import com.cwt_taxi_xa.model.VersionInfo;
import com.cwt_taxi_xa.protocol.DeviceBiz;

public class VersionBiz {
	private static final String TAG = "VersionBiz.";
	private Context context;
	private boolean versionflag = false;
	private boolean showDialog = false;
	private VersionInfo versionInfo;
	private ProgressDialog pBar;
	public static final String UPDATE_SAVENAME = "Wlgate.apk";

	public VersionBiz(Context context) {
		super();
		this.context = context;
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			int what = msg.what;
			if (what == 101) {
				doNewVersionUpdate();
			} else if (what == 102) {
				doCurrentVersion();
			} else if (what == 1023) {
				int nStep = msg.getData().getInt("step", -1);
				Log.d("", "step->" + nStep);
				if (nStep == -1)
					pBar.dismiss();
				else
					pBar.setProgress(nStep);
			} else if (what == 103) {
				/** 网络连接超时 */
				ToastUtils.showToastForCustom("服务器连接异常,请稍后再试");
			} else if (what == 104) {
				/** json解析错误 */
				ToastUtils.showToastForCustom("数据解析错误");
			} else if (what == 105) {
				/** 数据请求失败原因 */
				String message = (String) msg.obj;
				if (!StringUtil.isNull(message)) {
					ToastUtils.showToastForCustom(message);
				}
			} else if (what == 106) {
				/** 网络连接超时 */
				ToastUtils.showToastForCustom("网络连接超时");
			}
		};
	};

	/**
	 * 获取版本名称
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static int getVersion(Context context) throws Exception {
//		PackageManager packageManager = context.getPackageManager();
//		PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
//		return packInfo.versionCode;
		return Constants.localVersion;
	}

	/**
	 * 获取版本�?
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public int getVersionCode() throws Exception {
//		PackageManager packageManager = context.getPackageManager();
//		PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
//		return packInfo.versionCode;
		return Constants.localVersion;
	}

	/**
	 * 获取应用名称
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static String getAppName(Context context) {
		String verName = context.getResources().getText(R.string.app_name).toString();
		return verName;
	}

	public void doCheckVersion(final boolean needDialog) {
		showDialog = needDialog;
		/**
		 * 版本升级方式 0：多森平台 1：奇华平台
		 */
		doCheckVersionDSS(needDialog);
	}
	
	public static String getVersionJsonBody(){
		// http://taxi.jpfwpt.com:4657/rest/version
		//{"termno":"1025212","termType":1,"code":"wnjp"}
		String deviceCode = DeviceBiz.getDeviceCode();
		if(!TextUtils.isEmpty(deviceCode) || true){
		        JSONObject object = new JSONObject();
		        try {
		            object.put("termno", deviceCode);
		            object.put("termType", 1);//1-APP/2-MCU
		            object.put("code", Constants.PROJECT_CODE);
		            return object.toString();
		        } catch (JSONException e) {
		            e.printStackTrace();
		        }
		        return null;
		}else{
			AppLog.savelog("DeviceBiz.getDeviceCode() " + deviceCode);
		}
		return null;
	}

	/**
	 * 检查更新
	 * 
	 * @param context
	 * @return
	 */
	public void doCheckVersionDSS(final boolean needDialog) {
		// 判断网络是否连接 true 已连接 false 未连接
		boolean isConnected = ToastUtils.isConnect(MainApplication.getInstance().getApplicationContext());
		if (isConnected) {
			if (needDialog) {
				versionflag = true;
				ToastUtils.getInstance().popProgress((Activity) context, "正在检测新版本");
			}
			new AsyncTask<String, Void, Void>() {

				@Override
				protected Void doInBackground(String... params) {
					try {
						String url = "http://taxi.jpfwpt.com:4657/rest/version";
						OkHttpClient okHttpClient = new OkHttpClient();
						String jsonBody = getVersionJsonBody();
						Log.d(TAG, "checkVersion jsonBody:" + jsonBody);
						if (!TextUtils.isEmpty(jsonBody)) {
							RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
							Request request = new Request.Builder().url(url)// 请求的url
									.post(requestBody).build();
							Response response = okHttpClient.newCall(request).execute();
							String string = response.body().string();
							Log.e(TAG, "response ----->" + string);

							JSONObject obj = new JSONObject(string);
							int status = obj.getInt("errorcode");
							if (status == 0) {
								obj = obj.getJSONObject("data");
								int v = obj.getInt("version");
								AppLog.e("---------------------------" + v);

								// String url2 =
								// "http://taxi.jpfwpt.com:4657/apk/" + v +
								// "/wnjp/1";

								int locVersion = getVersion(context);

								versionInfo = new VersionInfo();
								versionInfo.setVersionId(v + "");
								// versionInfo.setDownloadPath("http://taxi.jpfwpt.com:4658/apk/"
								// + v + "/wnjp/1");
								versionInfo.setDownloadPath("http://taxi.jpfwpt.com:4657/apk/" + v + "/" + Constants.PROJECT_CODE + "/1");

								if (v != locVersion) {
									versionInfo.setType(1);
									handler.sendEmptyMessage(101);
								} else {
									if (versionflag) {
										versionInfo.setType(2);
										handler.sendEmptyMessage(102);
									}
								}
							} else {
								if (needDialog) {
									String message = obj.getString("message");
									handler.obtainMessage(105, message).sendToTarget();
								}
							}
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						if (needDialog) {
							handler.sendEmptyMessage(104);
						}
						e.printStackTrace();
						AppLog.e(ExceptionUtil.getInfo(e), e);

					} catch (Exception e) {
						// TODO Auto-generated catch block
						if (needDialog) {
							handler.sendEmptyMessage(103);
						}
						e.printStackTrace();
						AppLog.e(ExceptionUtil.getInfo(e), e);
					} finally {
						ToastUtils.getInstance().dismissCurrentDlg();
					}

					return null;
				}
			}.execute();
		} else {
			handler.sendEmptyMessage(106);
		}

	}
	
	
	/**
	 * 
	 * @param context
	 * @return
	 */
	public  static void doCheckSJInfor(final String number, final checkSJinfor listener) {
		// 判断网络是否连接 true 已连接 false 未连接
		boolean isConnected = ToastUtils.isConnect(MainApplication.getInstance().getApplicationContext());
		if (isConnected) {
			new AsyncTask<String, Void, Void>() {
				
				@Override
				protected Void doInBackground(String... params) {
					try {
						
						String url = null;
						url = "http://taxi.jpfwpt.com:4657/rest/getDriverInfo/"+number;
						HttpEntity httpEntity = HttpUtils.getEntity(url, null, HttpUtils.METHOD_POST);
						InputStream inputStream = HttpUtils.getStream(httpEntity);
						String json = StringParser.parse(inputStream);
						AppLog.e(json);
						JSONObject obj = new JSONObject(json);
						int status = obj.getInt("errorcode");
						if (status == 0) {
							obj = obj.getJSONObject("data");
							
							
							Constants.sijiinfo = new SijiInfo();
							
							Constants.sijiinfo.setSigninTpye(0);
							
							//姓名
							Constants.sijiinfo.setName(obj.getString("name"));
							
							//司机号
							Constants.sijiinfo.setSijicode(obj.getString("idcard"));
							
							//企业号
							Constants.sijiinfo.setQiyecode(obj.getString("certificateNo"));
							
							//资格证有效期
							Constants.sijiinfo.setCertificateData(obj.getString("certificateData"));
							
							//照片
							Constants.sijiinfo.setPhoto(DLPIC(listener, number, obj.getString("photo"), "司机照片"));
							
							//星级1-5
							Constants.sijiinfo.setStar(obj.getInt("star"));
							
							//所属公司
							Constants.sijiinfo.setCompanyname(obj.getString("company"));
							
							//监督电话
							Constants.sijiinfo.setMobile(obj.getString("mobile"));
							
							//二维码
//							Constants.sijiinfo.setQrCode1(DLPIC(number, obj.getString("qrCode1"), "二维码1"));
							
							//二维码
//							Constants.sijiinfo.setQrCode2(DLPIC(number, obj.getString("qrCode2"), "二维码2"));
							
							//卡号
							Constants.sijiinfo.setCardnum(obj.getString("cardnum"));
							
							Constants.sijiNow = true;
							
							//保存信息文本
							saveSijiInfo(number, Constants.sijiinfo, null);
							
						} else {
							listener.onInfor(false);
								String message = obj.getString("message");
								AppLog.e(message);
						}
						
					}catch (Exception e) {
						listener.onInfor(false);
						// TODO Auto-generated catch block
						e.printStackTrace();
						AppLog.e(ExceptionUtil.getInfo(e), e);
					} finally {
						ToastUtils.getInstance().dismissCurrentDlg();
					}
					return null;
				}
			}.execute();
		} else {
			AppLog.e("网络未连接，获取司机信息失败");
		}
		
	}
	//使用Gson更方便
	public static String fj = "-sijiinfo-";
	public static void saveSijiInfo(final String number, final SijiInfo info, final String[] ss){
		final String str =  info.getName() + fj
				+ info.getSijicode() + fj 
				+ info.getQiyecode() + fj 
				+ info.getCertificateData() + fj 
				+ info.getPhoto() + fj 
				+ info.getStar() + fj 
				+ info.getCompanyname() + fj 
				+ info.getMobile() + fj 
				+ info.getQrCode1() + fj 
				+ info.getQrCode2() + fj 
				+ info.getCardnum() + fj 
				+ info.getSigninTpye() + fj 
				+ info.getTermNumber() + fj 
				+ info.getStudentID() + fj 
				+ info.getIdentityNumber() + fj 
				+ info.getAddress() + fj 
				+ info.getAge() + fj 
				+ info.getPoliticalStatus() + fj 
				+ info.getAnnualAudit() + fj 
				+ info.getCertificateType() + fj 
				+ info.getDriverLicense() + fj 
				+ info.getDriverType() + fj 
				+ info.getDriverLicenseNumber() + fj 
				+ info.getDriverLicenseCD() + fj 
				+ info.getCertificateCD() + fj 
				+ info.getCardCD() + fj 
				+ info.getCertificateState() + fj 
				+ info.getSupervCardState() + fj 
				+ info.getSupervCardType() + fj 
				+ info.getSupervCardSDate() + fj 
				+ info.getSupervCardDDate();
		new Thread(){
			public void run() {
				try {
					File file = new File(Constants.SDPath+number); 
					if(!file.exists()){
						file.mkdir();
					}
					file=new File(Constants.SDPath+number+"/Info.txt");
					if(file.exists()) file.delete();
					FileOutputStream fileOutputStream=new FileOutputStream(file);
					fileOutputStream.write(str.getBytes());
					fileOutputStream.flush();
					fileOutputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
		
		if(ss!=null){
			new Thread(){
				public void run() {
					try {
						String str2 = "";
						for (int i = 0; i < ss.length; i++) {
							if(i==ss.length-1){
								str2+=(ss[i]);
							}else{
								str2+=(ss[i]+fj);
							}
						}
						File file = new File(Constants.SDPath+number); 
						if(!file.exists()){
							file.mkdir();
						}
						file=new File(Constants.SDPath+number+"/Info2.txt");
						if(file.exists()) file.delete();
						FileOutputStream fileOutputStream=new FileOutputStream(file);
						fileOutputStream.write(str2.getBytes());
						fileOutputStream.flush();
						fileOutputStream.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				};
			}.start();
		}
	}
	
	public static SijiInfo getSijiInfo(String num){
        try {
            File f=new File(Constants.SDPath+num+"/Info.txt");
            int length=(int)f.length();
            byte[] buff=new byte[length];
            FileInputStream fin=new FileInputStream(f);
            fin.read(buff);
            fin.close();
            String result = new String(buff);
            String[] ss = result.split(fj);
        
            if(ss.length >= 11){
            	SijiInfo info = new SijiInfo();
            	info.setName(ss[0]);
            	info.setSijicode(ss[1]);
            	info.setQiyecode(ss[2]);
            	info.setCertificateData(ss[3]);
            	info.setPhoto(ss[4]);
            	info.setStar(Integer.parseInt(ss[5]));
            	info.setCompanyname(ss[6]);
            	info.setMobile(ss[7]);
            	info.setQrCode1(ss[8]);
            	info.setQrCode2(ss[9]);
            	info.setCardnum(ss[10]);
            	try {
            	info.setSigninTpye(Integer.parseInt(ss[11]));
            	info.setTermNumber(Integer.parseInt(ss[12]));
				info.setStudentID(Integer.parseInt(ss[13]));
				info.setIdentityNumber(ss[14]);
				info.setAddress(ss[15]); 
				info.setAge(Integer.parseInt(ss[16])); 
				info.setPoliticalStatus(Integer.parseInt(ss[17]));
				info.setAnnualAudit(Integer.parseInt(ss[18])); 
				info.setCertificateType(Integer.parseInt(ss[19]));
				info.setDriverLicense(ss[20]); 
				info.setDriverType(Integer.parseInt(ss[21])); 
				info.setDriverLicenseNumber(ss[22]); 
				info.setDriverLicenseCD(ss[23]); 
				info.setCertificateCD(ss[24]);
				info.setCardCD(ss[25]);
				info.setCertificateState(Integer.parseInt(ss[26]));
				info.setSupervCardState(Integer.parseInt(ss[27]));
				info.setSupervCardType(Integer.parseInt(ss[28]));
				
				
					info.setSupervCardSDate(ss[29]);
					info.setSupervCardDDate(ss[30]);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					AppLog.e(" getSijiInfo " + e.getMessage());
				}
				
            	return info;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        
		return null;
	}
	
	public static String DLPIC(final checkSJinfor listener, final String number, final String iPath, final String name){
		final String path = Constants.SDPath+number+"/"+name+".jpg";
		new Thread(){
			public void run() {
				try {
					//对资源链接
					AppLog.e("网络照片：["+iPath+"]");
					URL url=new URL(iPath);
					//打开输入流
					InputStream inputStream=url.openStream();
					File file = new File(Constants.SDPath+number); 
					if(!file.exists()){
						file.mkdir();
					}
					
					file=new File(path);
					if(file.exists()) file.delete();
					FileOutputStream fileOutputStream=new FileOutputStream(file);
					int hasRead=0;
					while((hasRead=inputStream.read())!=-1){
						fileOutputStream.write(hasRead);
					}
					fileOutputStream.close();
					inputStream.close();
					
					listener.onInfor(true);
				} catch (Exception e) {
					e.printStackTrace();
					listener.onInfor(false);
				}
			};
		}.start();
		return path;
	}

	// 版本更新
	private void doNewVersionUpdate() {
		try {
			StringBuffer sb = new StringBuffer();
			String desc = versionInfo.desc;
			if (desc != null && desc.length() != 0 && !desc.equals("null")) {
				sb.append("更新内容:" + "\n\n");
				sb.append(desc);
			}
			Dialog dialog = new AlertDialog.Builder(context).setTitle("软件更新（" + versionInfo.getVersionId() + "）").setMessage(sb.toString())
			// 设置内容
					.setPositiveButton("更新",// 设置确定按钮
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									showPbar();
									// downFile("http://192.168.1.165/Dss_Driver.apk");
								}
							}).setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int whichButton) {
							dialog.dismiss();
						}
					}).create();
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
	}
	
	void showPbar(){
		pBar = new ProgressDialog(context);
		pBar.setCanceledOnTouchOutside(false);
		pBar.setTitle("正在下载");
		pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pBar.setButton( DialogInterface.BUTTON_POSITIVE,"下载不动？ 刷新一下~"
				,new DialogInterface.OnClickListener(){
			  public void onClick(DialogInterface d, int i) {
				  showPbar();
			  }
			}); 
		downFile(versionInfo.downloadPath);
	}

	long thisThreaddown = 0;
	void downFile(final String path) {
		pBar.show();

		Request request = new Request.Builder().url(path).build();
		new OkHttpClient().newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				// 下载失败
				e.printStackTrace();
				Log.i("DOWNLOAD", "download failed");
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				try {
					//这种莫名其妙的文件地址，获取不到总大小，只好用大概值代替
//					AppLog.e("总大小："+response.body().contentLength() );
					thisThreaddown = System.currentTimeMillis();
					final long thisthreadtime = thisThreaddown;
					
					
					pBar.setMax(19365);

					InputStream is = response.body().byteStream();// 从服务器得到输入流对象
					BufferedInputStream bis = new BufferedInputStream(is);

					File file = new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME);
					FileOutputStream fos = new FileOutputStream(file);

					byte[] buffer = new byte[1024];
					int len;
					int total = 0;
					
					boolean downok = true;
					while ((len = bis.read(buffer)) != -1) {
						if(thisthreadtime==thisThreaddown){
							fos.write(buffer, 0, len);
							total += len;
							Message msg = handler.obtainMessage();
							msg.getData().putInt("step", total / 1024);
							msg.what = 1023;
							handler.sendMessage(msg);
						}else{
							bis.close();
							is.close();
							downok = false;
							break;
						}
					}
					if(downok){
						fos.flush();
						fos.close();
						bis.close();
						is.close();
						down();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}

		});

	}

	void down() {
		handler.post(new Runnable() {
			@Override
			public void run() {
//				pBar.cancel();
				update();
			}
		});
	}

	void update() {

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME)), "application/vnd.android.package-archive");
		context.startActivity(intent);

		((Activity) context).finish();
	}

	private void doCurrentVersion() {
		StringBuffer sb = new StringBuffer();
		try {
			sb.append("当前版本号  " + getVersion(context) + ", 已是最新版本。");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}

		Dialog dialog = new AlertDialog.Builder(context).setTitle("软件更新").setMessage(sb.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		}).create();
		dialog.show();
	}
}
